const computedBehavior = require("miniprogram-computed");
const app = getApp();

import api from "../../../common/api";
import {setData} from "../../../models/transferData";
import p from "../../../utils/platform";
import util from "../../../utils/util.js";
import * as filterConfigs from "../../../models/filterConfigs"
import {getActiveStr} from '../../../utils/utilsNew';
Page({
  behaviors: [computedBehavior],

  /**
   * 页面的初始数据
   */
  data: {
    villageData: {},
    model: {
      room: "",
      hall: "",
      toilet: "",
      buildSize: "",
      totalPrices: "",
    },
    delegationType: "",
    sessionUser: {},
    imgArray: [],
    imgMin: 3,
    imgMax: 10, //最大图片数
    isSaving: false, //保存中
    moreValue: {
      feature: [],
      serviceLife: '',
      floor: '',
      decoration: '',
      orientation: '',
      notTheOnly: '',
    },
    moreOptions: [{
      id: 'serviceLife',
      title: '年限',
      red: '*',
      select: 'single',
      options: filterConfigs.serviceLife
    }, {
      id: 'notTheOnly',
      title: '是否唯一',
      red: '*',
      select: 'single',
      options: filterConfigs.notTheOnly
    }, {
      id: 'floor',
      title: '楼层',
      red: '*',
      select: 'single',
      options: filterConfigs.floor
    }, {
      id: 'decoration',
      title: '装修',
      red: '*',
      select: 'single',
      options: filterConfigs.decoration
    }, {
      id: 'orientation',
      title: '朝向',
      red: '*',
      select: 'single',
      options: filterConfigs.orientation
    }, {
      id: 'feature',
      title: '房源亮点',
      select: 'multi',
      options: filterConfigs.lightSpotType
    }],
    _buyPrice: '',
    isShowHouseTypeSheet: false,
    houseTypeOptions: [{
      id: 'room',
      title: '卧室数量',
      input: {
        unit: '室'
      },
      single: filterConfigs.room,
    }, {
      id: 'hall',
      title: '客厅餐厅数量',
      input: {
        unit: '厅'
      },
      single: filterConfigs.hall
    }, {
      id: 'toilet',
      title: '卫生间数量',
      input: {
        unit: '卫'
      },
      single: filterConfigs.toilet
    }],
    isShowDataDetection: false, //用来控制数据监测弹窗的显示
    _houseTitle: "", //房源标题
    backFromInputTextValuePageCb: null, //从页面回来的回调
    valueLength: '0',
    textInfo: '',
    endTime: '', //挂牌时间的截至时间
    chlikData: '', //默认选中的挂牌时间
    inputFloorNum: '', //楼层位于
    dataDetectionInfo: '', //检测弹窗需要的数据
  },

  computed: {
    isPublishAble(data) {
      const {
        moreValue,
        model,
        delegationType,
        _houseTitle
      } = data || {}
      return (
        model.room &&
        model.hall &&
        model.toilet &&
        model.buildSize && model.buildSize !== '0' &&
        model.totalPrices && model.totalPrices !== '0' &&
        data.imgArray.length >= data.imgMin &&
        (delegationType === 'SALES' ? moreValue.serviceLife &&
          _houseTitle!==''&&
          moreValue.floor &&
          moreValue.decoration &&
          moreValue.notTheOnly &&
          moreValue.orientation : true)
      );
    },
    $_houseTitle(data) {
      return getActiveStr(data._houseTitle, 30)
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let villageData = JSON.parse(options.villageData);
    this.data.villageData = villageData;
    // picker组件 限制末端时间
    let nweTime = new Date().getTime()
    nweTime = util.dateFormat(new Date(nweTime), "yyyy-MM-dd")
    this.setData({
      delegationType: app.getCurrentStatusName(),
      _houseTitle: villageData.resblockName,
      endTime: nweTime
    });
    app.globalData.loginPromise.then(({
      sessionUser
    }) => {
      this.data.sessionUser = sessionUser;
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.backFromInputTextValuePageCb) {
      this.data.backFromInputTextValuePageCb()
      this.data.backFromInputTextValuePageCb = null
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  // 发布合作房源
  handleSave() {
    if (!this.data.isPublishAble) return;
    if (this.data.isSaving) return wx.showToast({
      title: `操作过于频繁!`,
      icon: "none",
    });
    this.data.isSaving = true
    this.createBuilding()
      .then(({
        houseId,
        buildingId
      }) => {
        return this.houseAndCommissionNew(houseId);
      })
      .then((houDelId) => {
        api.publishCooperationHouse([houDelId], ({
          data
        }) => {
          setData("isRefreshCooperation", true);
          p.showModal({
            title: "发房成功",
            content: "合作房源已发布成功，请及时关注IM的合作咨询消息~",
            confirmText: "继续发布",
            cancelText: "查看房源",
          }).then(({
            confirm
          }) => {
            this.data.isSaving = false
            if (confirm) {
              wx.reLaunch({
                url: "/pages/cooperation/publishIndex/publishIndex"
              });
            } else {
              wx.reLaunch({
                url: "/pages/index/index?tabConentName=合作"
              });
            }
          });
        }, () => {
          this.data.isSaving = false
        });
      });
  },

  createBuilding() {
    return new Promise((resolve, reject) => {
      var inputData = {
        hdResblockId: this.data.villageData.hdResblockId,
        resblockId: this.data.villageData.resblockId,
        buildingNum: "",
        totalFloor: "",
        floor: "",
        roomNo: "",
        unit: "",
      };
      api.addCreateBuilding(JSON.stringify(inputData), ({
        data
      }) => {
        resolve(data.content);
      });
    });
  },


  // 发房的接口
  houseAndCommissionNew(houseId) {
    return new Promise((resolve, reject) => {
      const {
        moreValue,
        _buyPrice,
        chlikData,
        _houseTitle,
        textInfo,
        inputFloorNum
      } = this.data
      const {
        room,
        hall,
        toilet,
        buildSize,
        totalPrices,
      } = this.data.model || {}

      const villageData = this.data.villageData;
      const sessionUser = this.data.sessionUser;
      const lightSpot = this.featureSort(moreValue.feature)
      const imgs = this.data.imgArray.map((item, i) => {
        return {
          fileId: item.fileId,
          houDelId: "",
          tagCode: "",
          tagName: "未选择",
          cover: i,
          url: "",
        };
      });
      let finalRoom = this.isWhatType(room) === 'Object' ? room.input : room || '';
      let finaltHall = this.isWhatType(hall) === 'Object' ? hall.input : hall || '';
      let finaltToilet = this.isWhatType(toilet) === 'Object' ? toilet.input : toilet || '';

      let allPostData = {
        userId: sessionUser.id,
        storeId: sessionUser.extProps.storeId,
        houseId,
        hdHouseId: "",
        addr: this.data.villageData.addr,
        delegationType: this.data.delegationType,
        room: finalRoom,
        hall: finaltHall,
        toilet: finaltToilet,
        elevatorNum: "",
        roomNum: "",
        buildSize: buildSize || '',
        buildType: "",
        schoolOccupy: "",
        propertyRight: {
          propetyType: "",
          loanInfo: ""
        },
        unit: "",
        floor: "",
        totalFloor: "",
        roomNo: "",
        del: {
          title: `${villageData.resblockName} ${finalRoom}室${finaltHall}厅${finaltToilet}卫`,
          totalPrices: this.data.delegationType == "SALES" ? totalPrices : "",
          rent: this.data.delegationType == "RENT" ? totalPrices : "",
          fkfsf: "",
          fkfsy: "",
          approTime: "",
          salesTag: [],
          rentTag: [],
          decorateType: moreValue.decoration || '',
          houYears: moreValue.serviceLife || '',
        },
        direction: moreValue.orientation || '',
        buildNumNew: moreValue.floor || '',
        imgs,
        lightSpot,
        buyPrice: _buyPrice? (_buyPrice*10000) : '',
        unique: moreValue.notTheOnly || '', //是否唯一
        listingTime: chlikData || '', //挂牌时间
        notes: textInfo || '', //房源简介
        title: _houseTitle || '', //房源标题
        floorHight: inputFloorNum || '', //楼高

      };
      api.addHouseSaveNew(JSON.stringify(allPostData), (res) => {
        let houDelId = res.data.content;
        resolve(houDelId);
      });
    });
  },

  handleCancel(e) {
    let id = e.currentTarget.dataset.fileid;

    this.setData({
      imgArray: this.data.imgArray.filter((v) => v.fileId != id),
    });
  },

  handleSelectImg() {
    let num = this.data.imgMax - this.data.imgArray.length;
    if (num == 0) return wx.showToast({
      icon: "none",
      title: "已达最大图片数！"
    });

    wx.chooseImage({
      sourceType: ["album"], // 从相册选择
      count: num,
      success: (res) => {
        let filePathArr = res.tempFilePaths;
        let promiseList = filePathArr.map((item) => {
          return new Promise((resolve, reject) => {
            util.uploadFiles(item, (res) => {
              try {
                var id = JSON.parse(res.data)[0].id;
                var obj = {
                  fileId: id,
                  url: item,
                };
                resolve(obj);
                
              } catch (error) {
                reject()
              }
            });
          });
        });

        Promise.all(promiseList).then((list) => {
          let arr = this.data.imgArray.concat(list);
          arr.length = Math.min(arr.length, this.data.imgMax);
          this.setData({
            imgArray: arr,
          });
        });
      },
    });
  },

  inputTotalPrices(e) {
    this.setData({
      "model.totalPrices": e.detail.value,
    });
  },

  inputBuyPrice(e) {
    this.data._buyPrice = e.detail.value
  },

  inputBuildSize(e) {
    this.setData({
      "model.buildSize": e.detail.value,
    });
  },

  featureSort(data) {
    if (!(data && data.length)) {
      return []
    }
    let newData = JSON.parse(JSON.stringify(data))
    newData.sort((a, b) => {
      return filterConfigs.lightSpotType.findIndex((v) => v.value == a) - filterConfigs.lightSpotType.findIndex((v) => v.value == b)
    })
    return newData
  },

  onInfoTypeChange(e) {
    let id = e.currentTarget.dataset.id
    let data = e.detail
    let path = `moreValue.${id}`
    this.setData({
      [path]: data
    })
  },

  onClickHouseType() {
    this.setData({
      isShowHouseTypeSheet: true,
    })
  },

  onHouseTypeClose() {
    this.setData({
      isShowHouseTypeSheet: false,
    })
  },

  onHouseTypeChange(e) {
    const {
      hall,
      room,
      toilet
    } = e.detail.form || {}
    this.setData({
      'model.hall': hall,
      'model.room': room,
      'model.toilet': toilet,
    })
  },

  isWhatType(o) {
    return Object.prototype.toString.call(o).slice(8, -1)
  },


  // 2021-07-08 合作房源修改
  handleHide(e) {
    let visible = e.detail.visible
    this.setData({
      isShowDataDetection: visible
    })
  },
  backButtom() {
    this.setData({
      isShowDataDetection: false
    })
  },
  confirmButtom() {
    if (this.data.isSaving) return wx.showToast({
      title: `操作过于频繁!`,
      icon: "none",
    });
    this.data.isSaving = true
    this.createBuilding()
      .then(({
        houseId
      }) => {
        return this.houseAndCommissionNew(houseId);
      })
      .then((houDelId) => {
        let authenticityCheckId = this.data.dataDetectionInfo.authenticityCheckId
        api.publishCooperationHouseAddId([houDelId], authenticityCheckId, ({
          data
        }) => {
          this.data.isSaving = false
          setData("isRefreshCooperation", true);
          if (data && data.isSuccess) {
            wx.showToast({
              title: '合作房源发布成功',
              icon: 'none',
              duration: 1000
            })
            wx.redirectTo({
              url: '/pages/index/index?tabConentName=合作',
            })
          } else {
            wx.showToast({
              title: '合作房源发布失败',
              icon: 'none',
              duration: 1000
            })
          }
        });
      });
  },

  // 修改标题
  titleEditButton() {
    app.globalData.inputTextValuePage = this.data._houseTitle
    p.navigateTo({
      url: `/pages/addHouse/inputTextValue/inputTextValue?placeholder=请输入房源标题&maxCount=20`
    })
    this.data.backFromInputTextValuePageCb = () => {
      this.setData({
        _houseTitle: app.globalData.inputTextValuePage
      })
      app.globalData.inputTextValuePage = ""
    }
  },
  // 动态获取输入的值
  dynamicValue(e) {
    let value = e.detail.value
    this.setData({
      valueLength: value.length,
      textInfo: value
    })
  },
  bindDateChange(e) {
    this.setData({
      chlikData: e.detail.value
    })
  },

  inputFloorNum(e) {
    let inputFloorNum = e.detail.value
    if (inputFloorNum && inputFloorNum !== '' && inputFloorNum !== undefined) {
      let num = /^([1-9]{1}[0-9]{0,1}$)/g.test(inputFloorNum)
      if (num) {
        this.setData({
          inputFloorNum
        })
      } else {
        wx.showToast({
          title: '只允许输入正整数，最大只能输入99',
          icon: 'none',
          duration: 2000
        })
      }
    }
  },
  // 检测房源
  handleSaveSALES() {
    if (!this.data.isPublishAble) return;
    return new Promise((resolve, reject) => {
      if (this.data.isSaving) return wx.showToast({
        title: `操作过于频繁!`,
        icon: "none",
      });
      this.data.isSaving = true
      const {
        buildSize,
        totalPrices,
      } = this.data.model || {}
      let inputData = {
        hdResblockId: this.data.villageData.hdResblockId,
        buildSize,
        totalPrices
      };
      api.authenticityCheck(inputData, (res) => {
        if (res && res.data && res.data.isSuccess) {
          let results = res.data.content
          if (results.buildSizeCheck == 0 && results.totalPricesCheck == 0) { //面积和价钱都没有匹配结果
            this.data.isSaving = false
            this.confirmButtom()
            this.data.dataDetectionInfo = results
          } else {
            this.setData({
              isSaving:false,
              isShowDataDetection: true,
              dataDetectionInfo: results
            })
          }
          
          resolve()
        } else {
          wx.showToast({
            title: '接口异常',
            icon: 'none',
            duration: 2000
          })
        }
      })
    })
  },
});